package faf.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import faf.business.QuestionManager;
import faf.business.SheetManager;
import faf.business.SurveyManager;
import faf.business.UserManager;
import faf.entities.Account;
import faf.entities.Properties;
import faf.entities.Question;
import faf.entities.Sheet;
import faf.entities.Survey;

public class CreateQuestionController implements Controller {

	SurveyManager surveyManager;
	UserManager userManager;
	QuestionManager questionManager;
	SheetManager sheetManager;
	long id;

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Map<String, Object> surveyModel = new HashMap<String, Object>();
		Survey survey = new Survey();

		Account account = (Account) request.getSession().getAttribute("user");
		if (account == null) {
			return new ModelAndView("login");
		}

		if (request.getParameter("supprimer") != null) {
			long ids = Long.decode(request.getParameter("supprimer"));
			questionManager.deleteQuestion(ids);
		}

		if (request.getParameter("surveyFromList") != null) {
			id = Long.decode(request.getParameter("surveyFromList"));
		} else {
			id = Long.decode(request.getParameter("surveyFromEdit"));
		}
		survey = surveyManager.get(id);

		List<Sheet> Sheets = sheetManager.numberOfPolled(survey);
		int numberOfPolled = Sheets.size();
		List<Account> listAccount = new ArrayList<Account>();
		for (Sheet s : Sheets) {
			listAccount.add(s.getAccount());
		}

		List<Question> LQ = surveyManager.findListQuestion(survey.getId());
		surveyModel.put("survey", survey);
		surveyModel.put("questions", LQ);
		surveyModel.put("listAccount", listAccount);
		surveyModel.put("numberOfPolled", numberOfPolled);
		surveyModel.put("size", LQ.size());

		return new ModelAndView("addquestion", "model", surveyModel);
	}

	public void setSheetManager(SheetManager sheetManager) {
		this.sheetManager = sheetManager;
	}

	public void setQuestionManager(QuestionManager questionManager) {
		this.questionManager = questionManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setSurveyManager(SurveyManager surveyManager) {
		this.surveyManager = surveyManager;
	}

}
